package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class StaticHandler implements HttpHandler {

    static final File folder = new File("../civilopedia-website/static");
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {

        String uriPath = httpExchange.getRequestURI().getPath();

        File f = new File(folder, uriPath);
        if (f.exists()) {
            InputStream in = new FileInputStream(f);
            httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, in.available());
            OutputStream out = httpExchange.getResponseBody();
            byte[] b = new byte[64];
            int len;
            while ((len = in.read(b, 0, b.length)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } else {
            System.out.println("Not Found : " + uriPath);
            httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0);
        }

        httpExchange.close();
    }
}